package com.witdata.framework.service.docker.impl;

import com.alibaba.fastjson2.JSON;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.docker.Image;
import com.witdata.common.domain.docker.InstanceImage;
import com.witdata.common.domain.dto.InstanceDto;
import com.witdata.common.exception.GlobalException;
import com.witdata.framework.service.docker.DockerImageService;
import com.witdata.rabbit.domain.Handle;
import com.witdata.rabbit.producer.InstanceProducer;
import com.witdata.rabbit.service.InstanceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DockerImageServiceImpl implements DockerImageService {
    private final InstanceProducer instanceProducer;
    private final InstanceService instanceService;

    @Override
    public List<Image> getImageList(Long instanceId) {
        InstanceDto instanceDto = instanceService.getInstanceById(instanceId);
        if (ObjectUtils.isEmpty(instanceDto)) throw new GlobalException(Status.INSTANCEISNOTEXISTS);
        if (instanceDto.getStatus().equals(InstanceDto.Status.Offline)) throw new GlobalException(Status.INSTANCEOFFLINE);
        String data = instanceProducer.send(instanceId, Handle.GetImageList, null);
        return JSON.parseArray(data, Image.class);
    }

    @Override
    public void removeImage(InstanceImage instanceImage) {
        Image image = Image.builder()
                .id(instanceImage.getImageId())
                .build();
        instanceProducer.send(instanceImage.getInstanceId(), Handle.RemoveImage, image);
    }

    @Override
    public void pullImage(InstanceImage instanceImage) {
        Image image = Image.builder().tag(instanceImage.getTag()).build();
        System.out.println("image = " + image);
        instanceProducer.send(instanceImage.getInstanceId(), Handle.PullImage, image);
    }
}
